//
//  LiveViewController.m
//  ios_news
//
//  Created by Han on 14-6-9.
//  Copyright (c) 2014年 ucoder. All rights reserved.
//

#import "LiveViewController.h"
#import "LiveDetailController.h"
#import "NewsDetailController.h"
#import "Util.h"
#import "LiveNews.h"
#import "LiveNewsCell.h"

@implementation LiveViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 夜间模式监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doThemeChanged:)name:@"themeChange" object:nil];
    
    self.navigationController.navigationBar.barTintColor = MAIN_COLOR;
    self.navigationController.navigationBar.translucent = NO;  // 半透明
    self.navigationController.navigationBar.hidden = NO;
    
    self.navigationItem.title = @"直播中...";
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    
    
    mData = [NSMutableArray arrayWithCapacity:30];
    
    
    float mTableViewHeight = GLOBLE_HEIGHT - 64 - 49; // nav 64 tabar 49
    
    mTableView = [[LiveTableView alloc] initWithFrame:CGRectMake(0, 0, 320, mTableViewHeight)];
    
    mTableView.delegate = self;
    mTableView.dataSource = self;
    
    [self.view addSubview:mTableView];
    
    
    // 刷新头
    mRefreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - mTableView.bounds.size.height, mTableView.frame.size.width, mTableView.bounds.size.height)];
    
    mRefreshHeaderView.delegate = self;
    [mTableView addSubview:mRefreshHeaderView];
    
    
    
    [self loadData: NO];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    [MobClick beginLogPageView:@"LiveViewController"];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [MobClick endLogPageView:@"LiveViewController"];
}



- (void) loadData: (BOOL)isFresh
{
    
    NSString *cacheKey = @"cache_live_news_list_0";
    
    /*
    
    // 从缓存读取数据
    if (!isFresh) {
        NSLog(@"FromCache");
        
        mList = (LiveNewsList *)[Util readObject:cacheKey];
        
        if (mList == nil) {
            [self loadData:YES];
        } else {
            [mData addObjectsFromArray:mList.dataList];
            //NSLog(@"%@", list.dataList);
            [mTableView reloadData];
            
            [self checkDataExpireStatus];
        }
        
        return;
    }
     */
    
    // 从服务器读取数据
    NSString *url = [[NSString alloc] initWithFormat:@"%@%d", API_LIVE_NEWS, 0];
    
    NSURLSessionTask *task1 = [LiveNewsList getDataWithBlock:^(LiveNewsList *list, NSError *error) {
        if (!error) {
            [mRefreshHeaderView refreshLastUpdatedDate];
            
            NSLog(@"FromHttp");
            
            // NSLog(@"%f", list.updateTime);
            
            [mData addObjectsFromArray:list.dataList];
            
            [Util saveObject:list withFileName:cacheKey];
            
            //NSLog(@"%@", mData);
            [mTableView reloadData];
            
        } else {
            NSLog(@"%@", error);
        }
    } :url];
    
    
}


- (void) checkDataExpireStatus {
    
    //NSLog(@"%f", mList.updateTime - [[NSDate date] timeIntervalSince1970]);
    if ([[NSDate date] timeIntervalSince1970] - mList.updateTime > 30) {
        
        
        [self triggerPullDownRefresh];
    }

}

#pragma mark - private methods
-(void) triggerPullDownRefresh
{
    [mTableView setContentOffset:CGPointMake(0, -75) animated:YES];
    [self performSelector:@selector(doneManualRefresh) withObject:nil afterDelay:0.4];
}

-(void)doneManualRefresh
{
    [mRefreshHeaderView egoRefreshScrollViewDidScroll:mTableView];
    [mRefreshHeaderView egoRefreshScrollViewDidEndDragging:mTableView];
}


- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //NSMutableArray *currentData = [mData objectAtIndex:mCurrentPage];
    
    //NSLog(@"currentData count = %i", [currentData count]);
    
    static NSString *CellIdentifier = @"NewsListCell";
    LiveNewsCell *cell = (LiveNewsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[LiveNewsCell alloc] initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:CellIdentifier];
    }
    
    cell.liveNews = [mData objectAtIndex:(NSUInteger)indexPath.row];
    
    return cell;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [mData count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
    LiveNews *new = [mData objectAtIndex:indexPath.row];
    float textHeight = [Util getTextHeightWithString:[Util formatHtmlString:new.content]
                                                font:[UIFont systemFontOfSize:16.0f]
                                            andWidth:320-39];
    
    return textHeight;
    */
    return 100;
}


#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
	[self reloadTableViewDataSource];
	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.5];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
	return mReloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
	
	return [NSDate date]; // should return date data source was last changed
	
}


- (void)reloadTableViewDataSource
{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	mReloading = YES;
	
}

- (void)doneLoadingTableViewData
{
	
	//  model should call this when its done loading
	mReloading = NO;
    
	[mRefreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mTableView];
	
}

// 滚动就触发
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    
    [mRefreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
        
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [mRefreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}


- (void)doThemeChanged:(NSNotification*) notification
{
    if ([notification.name isEqualToString:@"themeChange"]) {
        NSLog(@"NewsViewController - themeChange");
        if ([Util isNightMode]) {
            self.view.backgroundColor = ColorWithRGB(34, 34, 34);
        } else {
            self.view.backgroundColor = ColorWithRGB(236, 236, 236);
        }
        
    }
}


- (void) pushView:(id)sender {

    LiveDetailController *liveDetailCtr = [[LiveDetailController alloc] init];
    liveDetailCtr.hidesBottomBarWhenPushed = YES; // 详情页隐藏tabbar
    //NewsDetailController *liveDetailCtr = [[NewsDetailController alloc] init];
    [self.navigationController pushViewController:liveDetailCtr animated:YES];
}

@end
